package org.openotdr.client;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FileUpload;

public class FileUploadComposite extends Composite {

	public FileUploadComposite() {
		
		final VerticalPanel verticalPanel = new VerticalPanel();
		initWidget(verticalPanel);
		
		final FormPanel formPanel = new FormPanel();
		verticalPanel.add(formPanel);
		formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
		formPanel.setMethod(FormPanel.METHOD_POST);
		
		final FileUpload fileUpload = new FileUpload();
		fileUpload.setName("fileUpload");
		formPanel.setWidget(fileUpload);
		fileUpload.setSize("100%", "100%");
		final HTML html = new HTML();
		fileUpload.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				String[] s = fileUpload.getFilename().split("\\\\");
				formPanel.setAction("/fileServlet?filetype=sr4731&filename=" + s[s.length-1]);
				formPanel.submit();
			}
		});
		
		formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
				HTML html = new HTML();
				verticalPanel.add(html);
				html.setHTML("<A HREF=\"" + event.getResults() + "\">Download</A>");
			}
		});
	}

}
